<?php
//开启session
session_start();
//判断用户是否登录
if(!isset($_SESSION['username']) || !isset($_SESSION['id'])){
	echo '<script>alert("请先登录,再发帖子");window.location.href="list.php?cid='.$cid.'";</script>';
	exit;
}
//包含数据库配置文件
include '../public/dbconfig.php';
//包含函数库文件
include '../public/functions.php';
//调用函数 链接数据库
$link = con();
//接收用户传过来的信息
//接收帖子标题
$title = $_POST['title'];
//接收帖子内容
$content = $_POST['content'];
//验证码
$yzm = $_POST['yzm'];
//接收版块id
$cid = $_POST['cid'];
//获取用户的ip
$ip = $_SERVER['REMOTE_ADDR'];
//获取发帖时间
$rtime = time();
//判断用户是否添加附件
if($_FILES['file']['error'] != 4){
	$file = upload('file','../images/');
}

//判断ip 如果是::1 就转换 127.0.0.1  否则就直接转换
if($ip = '::1'){
	$rip = ip2long('127.0.0.1');
}else{
	$rip = ip2long($ip);
}

//判断该ip是否已被禁用
$ipsql = "select ip from ip where ip={$rip}";
//执行sql
$ipres = mysqli_query($link, $ipsql);
//判断执行结果
if($ipres && mysqli_num_rows($ipres)){
	echo '<script>alert("该ip已被管理员禁用,暂不能发帖");window.location.href="post.php?cid='.$cid.'";</script>';
	exit;
}

$fmoney = 0;
//判断是否是购买贴
if($_POST['money'] != ''){
	$fmoney = $_POST['money'];
}

//判断标题是否为空
if(empty($title)){
	echo '<script>alert("标题不能为空");window.location.href="post.php?cid='.$cid.'";</script>';
	exit;
}
//判断内容是否为空
if(empty($content)){
	echo '<script>alert("内容不能为空");window.location.href="post.php?cid='.$cid.'";</script>';
	exit;
}
//判断标题长度
$titlelen = strlen($title);
if($titlelen > 80){
	echo '<script>alert("标题字符最多80个");window.location.href="post.php?cid='.$cid.'";</script>';
	exit;
}

//判断内容长度
$contentlen = strlen($content);
if($contentlen > 500){
	echo '<script>alert("帖子内容字符最多500个");window.location.href="post.php?cid='.$cid.'";</script>';
	exit;
}

//判断验证码
if($yzm != $_SESSION['yzmstr']){
	echo '<script>alert("验证码不正确");window.location.href="post.php?cid='.$cid.'";</script>';
	exit;
}

//查询词语过滤表
$filsql = "select id,name,rname from filter";
//执行sql
$filres = mysqli_query($link, $filsql);
//判断执行结果
if($filres && mysqli_num_rows($filres)){
	while($filter = mysqli_fetch_assoc($filres)){
		$name[] = $filter['name'];
		$rname[] = $filter['rname'];
	}
}
//替换内容
$content = str_replace($name,$rname,$content);

//准备sql
$sql = "insert into ftiezi(uid,cid,title,content,rtime,rip,fujian,money)values('{$_SESSION['id']}','{$cid}','{$title}','{$content}','{$rtime}','{$rip}','{$file}','{$fmoney}')";
//执行sql
$res = mysqli_query($link, $sql);
//判断执行结果
if($res){
	//查询用户金钱
	$jqsql = "select money from user where id={$_SESSION['id']}";
	//执行sql
	$jqres = mysqli_query($link, $jqsql);
	//赋值
	$umoney = mysqli_fetch_assoc($jqres);
	//释放结果集
	mysqli_free_result($jqres);
	
	//准备修改用户金钱
	$xgsql = "update user set money={$umoney['money']} + 200 where id={$_SESSION['id']}";
	//执行sql
	$xgres = mysqli_query($link, $xgsql);
	
	echo '<script>alert("发表成功,奖励200人名币");window.location.href="list.php?cid='.$cid.'";</script>';
}else{
	echo '<script>alert("发表失败");window.location.href="list.php?cid='.$cid.'";</script>';
}
//关闭数据库链接
mysqli_close($link);